package com.airplane.auto.util;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;

import com.airplane.auto.service.MyNotification;

public class AlarmUtil {
	
	public static void runAlarm(Context mContext,String planTime,boolean enabling){
    	if(!ConfigCenter.getValue(mContext, Constants.ENABLE_AUTO_CHANGE, true)){	
    		return;
    	}
    	   Calendar c = Calendar.getInstance();
    	   String now = DateUtil.getCurrentDate("HHmm");
    	   planTime = planTime.replace(":", "");
    	   
    	   int hour = Integer.valueOf(planTime.substring(0,2));    	   
    	   int minute = Integer.valueOf(planTime.substring(2,4));
    	   
    	   //设置的时间刚好是现在则直接启动开关
    	   if(Integer.valueOf(now)==Integer.valueOf(planTime)){
    		   changeAirPlaneMode(mContext,enabling);
    		   return;
    	   }
    	   
    	   //如果计划的时间比现在小，则加1天
    	   if(Integer.valueOf(now)>Integer.valueOf(planTime)){
    		   c.add(Calendar.DAY_OF_MONTH, 1);
    	   }
    	   c.set(Calendar.HOUR_OF_DAY, hour);
    	   c.set(Calendar.MINUTE, minute);
    	   c.set(Calendar.SECOND, 0);
    	   
    	   /* 指定闹钟设置时间到时要运行CallAlarm.class */
	       Intent i = new Intent(mContext,MyNotification.class);
	       i.putExtra("state", enabling);
	       	       
	       PendingIntent sender = null;
	       if(enabling){
	    	   sender = PendingIntent.getBroadcast(mContext,1, i, 0);
	       }else{
	    	   sender = PendingIntent.getBroadcast(mContext,2, i, 2);
	       }
	       
	       //先取消
	       AlarmManager  am = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
	       am.cancel(sender);
	       
	       //间隔时间	       
	       int times= 24*60*60*1000;
	       
	       /* setRepeating()可让闹钟重复运行 */
	       am.setRepeating(AlarmManager.RTC_WAKEUP,
	                 c.getTimeInMillis(),times,sender);
	       
	       
    }
	
	public static void changeAirPlaneMode(Context mContext, boolean enabling){
     	 // Change the system setting
         Settings.System.putInt(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 
                                 enabling ? 1 : 0);
         
         // Post the intent
         Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
         intent.putExtra("state", enabling);
         mContext.sendBroadcast(intent);
     }

}
